package com.china_goldcard.igas.http.base;

import com.china_goldcard.igas.enums.RespCode;
import com.china_goldcard.igas.exception.AppException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import rx.Subscriber;

/**
 * 响应结果订阅者
 */
public class RespSubscriber<T extends HttpRespResult> extends Subscriber<T> {

    private ReqHandler<HttpRespResult> reqHandler;

    public RespSubscriber(ReqHandler<HttpRespResult> reqHandler){
         this.reqHandler = reqHandler;
    }

    @Override
    public void onStart() {
        this.reqHandler.onStart();
    }

    @Override
    public void onCompleted() {
        this.reqHandler.onDone();
    }

    @Override
    public void onError(Throwable e) {
        String responseCode = RespCode.DefaultError.getValue();
        String message = "";
        if (e instanceof SocketTimeoutException) {
            message = "网络中断，请检查您的网络状态";
        } else if (e instanceof ConnectException) {
            message = "网络中断，请检查您的网络状态";
        } else if (e instanceof AppException){
            message = ((AppException) e).getErrorMsg();
        }else{
            message =  e.getMessage();
        }
        HttpRespResult result = new HttpRespResult();
        result.setMessage(message);
        result.setResponseCode(responseCode);
        reqHandler.onNetFail(result);
    }

    @Override
    public void onNext(HttpRespResult httpResult) {
        if(httpResult.isSucc()){
            reqHandler.onSuccess(httpResult);
        }else{
            reqHandler.onFail(httpResult);
        }
    }
}
